package lock.reetrant;

import junit.framework.TestCase;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zhangxin
 * @date 2020/9/23
 */
public class Test extends TestCase {

    public static void main(String[] args) {

        long between = ChronoUnit.DAYS.between(LocalDate.now(), LocalDate.now());

        if (between < 0 || between > 7) {

        }


        ReentrantLock lock = new ReentrantLock();
        try {
            lock.lockInterruptibly();
            System.out.println("Java");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

        lock.isHeldByCurrentThread();


        ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
        ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();

        test("test().........");
    }

    public static <T> void test(T t) {
        if (t instanceof String) {
            System.out.println(t);
        }
    }


    public void testLock() throws InterruptedException {

        ReentrantLock lock = new ReentrantLock();
        lock.lock();


        Thread thread = new Thread(() -> {
            lock.lock();
            try {
                Thread.sleep(30000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();

        Thread thread2 = new Thread(() -> {
            if (lock.tryLock()) {
                System.out.println("t2 get lock");
            }
            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread2.start();

        thread2.join();
    }


    @org.junit.Test
    public void testCondition() throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        Thread thread2 = new Thread(() -> {
            if (lock.tryLock()) {
                System.out.println("thread2 get lock");
            }
            try {
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread2.start();

        Thread.sleep(20L);


        Thread thread3 = new Thread(() -> {
            condition.signal();
            System.out.println("notify success");
        });
        thread3.start();

        Thread.sleep(2000L);

    }


}
